package com.lu.aio.server;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.lu.aio.ChannelHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @program lu-netty
 * @description: 读请求处理器
 * @author: zhanglu
 * @create: 2022-06-10 18:21:00
 */
@Slf4j
public class ReadCompletionHandler implements CompletionHandler<Integer, Object> {

    private AsynchronousSocketChannel channel;

    public ReadCompletionHandler(AsynchronousSocketChannel channel){
        if(this.channel == null){
            this.channel = channel;
        }
    }

    @Override
    public void completed(Integer result, Object msg) {
        byte[] bytes = msg.toString().getBytes(StandardCharsets.UTF_8);
        ByteBuffer attachment = ByteBuffer.allocate(bytes.length);
        attachment.flip();
        byte[] body = new byte[attachment.remaining()];
        attachment.get(body);
        try {
            String req = new String(body, CharsetUtil.UTF_8);
            log.info("server receive : "+ req);
            String currentTime = DateUtil.formatDateTime(new Date());
            byte[] bodyBytes = currentTime.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bodyBytes.length);
            writeBuffer.put(bodyBytes);
            writeBuffer.flip();
            channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer buffer) {
                    //如果没有发送完成，继续发送
                    if(buffer.hasRemaining()){
                        channel.write(buffer, buffer, this);
                    }
                }
                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void failed(Throwable exc, Object attachment) {

    }

}
